package com.qiaofang.collectmanagebff.facade.impl;


import com.qiaofang.collectmanage.stub.constants.HouseAgentResponseCode;
import com.qiaofang.collectmanagebff.facade.response.BaseRequest;
import com.qiaofang.collectmanagebff.service.config.ConfigUtils;
import com.qiaofang.collectmanagebff.service.util.upload.AbstractExcelUploader;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.util.LogUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/tool")
@Api(value = "中介数据--导入导出", tags = "tool")
public class ToolImplBff {

    private LogUtil logger = LogUtil.getLogger(ToolImplBff.class);

    @Autowired
    private AbstractExcelUploader uploadHouseAgentManager;

    /**
     * 下载新版房源采集公司中介模板
     */
    @GetMapping("/downloadHouseAgentTemplate")
    @ApiOperation(value = "新版房源采集-下载模板")
    public void downloadHouseAgentTemplate(HttpServletResponse response, HttpServletRequest request) {
        uploadHouseAgentManager.downloadTemplate(
                AbstractExcelUploader.SYS_PRO_TITLE_HOUSE_AGENT,
                AbstractExcelUploader.HOUSE_AGENT_TEMPLATE_MAP,
                response, request, "中介数据模板.xls");
    }

    @PostMapping("/importHouseAgentData")
    @ApiOperation(value = "新版房源中介-导入上传")
    public Map<String, Object> importHouseAgentData(@RequestParam("file") MultipartFile file,@RequestParam("createdUserName") String createdUserName) throws Exception {
        logger.info("新版房源中介-导入上传开始,大小{}B",file.getSize());
        Long startTime = System.currentTimeMillis();
        if (file != null && file.getSize() > ConfigUtils.getMaxSize() * 1024 * 1024) {
            throw new BusinessException(HouseAgentResponseCode.HOUSE_AGENT_UPLOAD_FILE_SIZE_MAX.getResponseCode(),HouseAgentResponseCode.HOUSE_AGENT_UPLOAD_FILE_SIZE_MAX.getResponseMessage());
        }
        final InputStream inputStream = file.getInputStream();
        final Map<String, Object> param = new HashMap<>();
        param.put("createdUserName",createdUserName);
        Map<String, Object> map = uploadHouseAgentManager.doUpload(inputStream, param);
        logger.info("新版房源中介-导入上传结束,用时{}", (System.currentTimeMillis() - startTime) / 1000 + "s");
        return map;
    }

    @PostMapping("/downloadFailureData")
    @ApiOperation(value = "中介信息-下载失败条目")
    public void downloadFailureData(@RequestBody BaseRequest<Long> importDate,  HttpServletResponse response) throws Exception {
        Long data = importDate.getData();
        uploadHouseAgentManager.downloadFailureData(data, response);
    }

}
